package com.qkm.xinguan.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qkm.xinguan.domain.entity.Trade;
import com.qkm.xinguan.domain.infrastructure.mapper.TradeMapper;
import com.qkm.xinguan.domain.infrastructure.security.LoginUser;
import com.qkm.xinguan.domain.infrastructure.utils.UserUtil;
import com.qkm.xinguan.exception.BusinessException;
import com.qkm.xinguan.repository.TradeRepository;
import com.qkm.xinguan.response.Result;
import com.qkm.xinguan.response.ResultCode;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("tradeService")
public class TradeRepositoryImpl extends ServiceImpl<TradeMapper, Trade> implements TradeRepository {


	@Override
	public Result getAllOrders(Long touristId) {
		int b=this.baseMapper.ifExist(touristId);
		if(b>0){
			// 根据 id列表查询订单
			List<Trade> trades = this.baseMapper.getOrderInfoByIds(touristId);
			return Result.ok().data(trades) ;
		}else {
			throw new BusinessException(ResultCode.ADD_ORDER_INFO.getCode(), "没有订单，请前往主页订购");
		}
	}

	@Override
	public Page<Trade> getTradeListPage(Integer page, Integer size) {
		LoginUser loginUser = UserUtil.getCurrentLoginUser();
		assert loginUser != null;
		LambdaQueryWrapper<Trade> wrapper=new LambdaQueryWrapper <>();
		wrapper.ne(Trade::getDeleted,1);
		wrapper.eq(Trade::getUserId,loginUser.getId());
		Page<Trade> p= this.baseMapper.selectPage(new Page<>(page, size), wrapper);
		return p;
	}

//	private Page<TradeVo> toTradeVoPage(Page<Trade> tradePage) {
//		Page<TradeVo> trade = new Page<>();
//		BeanUtils.copyProperties(tradePage, trade);
//		List<TradeVo> tradeVos = toTradeVoList(tradePage.getRecords());
//		trade.setRecords(tradeVos);
//		return trade;
//	}

//	private List<TradeVo> toTradeVoList(List<Trade> trades) {
//		if (trades.isEmpty()) {
//			return Collections.emptyList();
//		}
//		List<TradeVo> tradeVos = new ArrayList<>();
//		List<Long> userIds = houseInfos.stream().map(HouseInfo::getUserId).collect(Collectors.toList());
//		// 根据 部门id列表查询出对应的部门名称
//		List<String> userNames = userRepository.getUserNamesByIds(userIds);
//		AtomicInteger index = new AtomicInteger();
//		tradeVos.forEach(trade -> {
//			TradeVo tradeVo = executeVo(houseInfo, userNames.get(index.getAndIncrement()));
//			tradeVos.add(tradeVo);
//		});
//		return tradeVos;
//	}
//	public static TradeVo executeVo(Trade trade, String userName) {
//		TradeVo tradeVo = new TradeVo();
//		BeanUtils.copyProperties(trade, tradeVo);
//		tradeVo.setDaysRemain(50);
//		return tradeVo;
//	}

}
